package com.panshi.config;

import com.google.inject.internal.cglib.core.$ClassNameReader;
import com.panshi.shiro.CustomerRealm;
import com.panshi.shiro.PhoneRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean(name = "customerRealm")
    public CustomerRealm customerRealm(){
        return new CustomerRealm();
    }

    @Bean
    public PhoneRealm phoneRealm(){
        return new PhoneRealm();
    }


    @Bean(name = "defaultWebSecurityManager")
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("customerRealm")Realm customerRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(customerRealm);
        return securityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager")DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(securityManager);

        //添加shiro的内置过滤器,拦截
        /**
         * anon : 无需认证就可访问
         * authc : 必须认证了才可访问
         * user: 必须拥有 记住我 功能才能访问
         * perms : 拥有对每个资源的权限才能方法
         * role : 拥有某个角色权限才能访问
         */
        Map<String,String> filterMap = new LinkedHashMap<>();

        //无需授权的公共页面
        filterMap.put("/login","anon");
        filterMap.put("/kaptcha","anon");
        filterMap.put("/sendCodeLogin","anon");
        filterMap.put("/static/**","anon");

        //需要授权才能访问的页面
        filterMap.put("/","authc");

        factoryBean.setFilterChainDefinitionMap(filterMap);

        //设置登录的请求
        factoryBean.setLoginUrl("/login");

        //未授权页面
        factoryBean.setUnauthorizedUrl("/noauth");

        return factoryBean;
    }
}
